<template>
  <AppPage show-footer>
    <div class="mt-12 flex">
      <!----------------------------------------------------------------- 卡片一 ------------------------------------------------------------>
      <n-card class="w-50%" segmented>
        <n-tabs type="card" :animated="true" @before-leave="handleBeforeLeave" @update:value="handleUpdateValue">
          <!---------------------- 新订单 ------------------------>
          <n-tab-pane name="newOrder">
            <template #tab>
              <n-badge :value="waitOrderData.length" :offset="[6, 0]">
                新订单
              </n-badge>
            </template>
            <n-data-table
              :columns="columns" :data="waitOrderData" :loading="card1Load" :single-line="false"
              :pagination="pagination11"
            />
          </n-tab-pane>
          <!---------------------- 新订单 end ------------------------>
          <!---------------------- 已接单 ------------------------>
          <n-tab-pane name="confirmOrder">
            <template #tab>
              <n-badge :value="makingOrderData.length" :offset="[6, 0]">
                制作中
              </n-badge>
            </template>
            <n-data-table
              :columns="columns" :data="makingOrderData" :loading="card1Load" :single-line="false"
              :pagination="pagination12"
            />
          </n-tab-pane>
          <!---------------------- 已接单 end ------------------------>
        </n-tabs>
      </n-card>
      <!----------------------------------------------------------------- 卡片二 ------------------------------------------------------------>
      <n-card class="w-50%" segmented>
        <n-tabs type="card" :animated="true" @before-leave="handleBeforeLeave" @update:value="handleUpdateValue">
          <!---------------------- 堂食订单订单 ------------------------>
          <n-tab-pane name="newOrder1">
            <template #tab>
              <n-badge :value="inStoreOrder.length" :offset="[6, 0]">
                堂食订单
              </n-badge>
            </template>
            <n-data-table
              :columns="columns" :data="inStoreOrder" :loading="card2Load" :single-line="false"
              :pagination="pagination21"
            />
          </n-tab-pane>
          <!---------------------- 新订单 end ------------------------>
          <!---------------------- 外卖订单 ------------------------>
          <n-tab-pane name="confirmOrder2">
            <template #tab>
              <n-badge :value="outStoreOrder?.length" :offset="[6, 0]">
                外卖订单
              </n-badge>
            </template>
            <n-data-table
              :columns="columns" :data="outStoreOrder" :loading="card2Load"
              :single-line="false" :pagination="pagination22"
            />
          </n-tab-pane>
          <!---------------------- 已接单 end ------------------------>
        </n-tabs>
      </n-card>
    </div>
  </AppPage>
  <n-drawer v-model:show="printDrawerModel" :default-width="220" placement="left" resizable>
    <n-drawer-content title="打印预览">
      <template #header>
        <NButton type="primary" @click="printOrderFunction">
          开始打印
        </NButton>
      </template>
      <n-form
        id="printMe"
        label-placement="left" label-width="auto" :style="{
          maxWidth: '200px',
        }"
      >
        <n-form-item label-placement="left" label="订单号:">
          {{ printOrder.orderNum }}
        </n-form-item>
        <n-form-item label="姓名:">
          {{ printOrder.deliveryOrder?.userName }}
        </n-form-item>
        <n-form-item v-if="printOrder.deliveryOrder?.userPhone " label="手机号:">
          {{ printOrder.deliveryOrder?.userPhone }}
        </n-form-item>
        <n-form-item v-if="printOrder.deliveryOrder?.deliveryAddress " label="地址:">
          {{ printOrder.deliveryOrder?.deliveryAddress }}
        </n-form-item>
        <n-divider
          dashed :style="{
            marginTop: '0px',
            marginBottom: '0px',
            fontSize: '12px',
          }"
        >
          商品信息
        </n-divider>
        <n-form-item
          v-for="(item, index) in printOrder.items"
          :key="item.id" align-text
        >
          <template #label>
            商品{{ index + 1 }}*{{ item.goodsNum }}
          </template>
          {{ item.goodsName }}
          <n-hr />
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup>
import { useGlobalTask } from '@/store'
import { NButton, NPopconfirm, NPopover, NTag } from 'naive-ui'
import { h, ref } from 'vue'
import api from './api'

// const printShow = ref(false)// 打印视图
const router = useRouter()
const card1Load = ref(false)
const card2Load = ref(false)
const waitOrderData = ref([])// 待接单
const makingOrderData = ref([])// 制作中
const inStoreOrder = ref([])// 堂食订单
const outStoreOrder = ref([])// 待取货
const columns = [ // 表头
  {
    title: '单号',
    key: 'orderNum',
    width: 55,
    align: 'center',
    titleAlign: 'center',
    ellipsis: { tooltip: true },
    render: (rew) => {
      return h(
        NButton,
        { tag: 'a', text: true, onClick: () => openOrderDetailsModel(rew) },
        { default: () => rew.orderNum },
      )
    },
  },
  {
    title: '姓名',
    key: 'userName',
    width: 50,
    align: 'center',
    titleAlign: 'center',
  },
  {
    align: 'center',
    titleAlign: 'center',
    title: '取货方式',
    width: 50,
    key: 'deliveryTypeName',
    ellipsis: { tooltip: true },
    render: (row) => {
      if (row.deliveryType === 1) { // 待确认订单
        return h(
          NPopover,
          { trigger: 'hover' },
          {
            trigger: () => h(NButton, { type: 'error', tertiary: true, round: true }, () => row.deliveryTypeName),
            default: () => h('span', {}, row.deliveryAddress ? row.deliveryAddress : '堂食自取，本店地址'),
          },
        )
      }
      else { // 自配
        return h(
          NPopover,
          { trigger: 'hover' },
          {
            trigger: () => h(NButton, { type: 'warning', tertiary: true, round: true }, () => row.deliveryTypeName),
            default: () => h('span', {}, row.deliveryAddress ? row.deliveryAddress : '堂食自取，本店地址'),
          },
        )
      }
    },
  },
  {
    title: '商品信息',
    align: 'center',
    titleAlign: 'center',
    width: 120,
    ellipsis: {
      tooltip: true,
    },
    render: (row) => {
      if (row.items?.length) {
        return row.items.map(i =>
          h(
            NTag,
            {
              type: 'primary',
              bordered: false,
              round: true,
            },
            {
              default: () => ` ${i.goodsName}*${i.goodsNum} `,
            },
          ),
        )
      }
      return '暂无标签'
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    align: 'center',
    fixed: 'right',
    render(row) {
      // 根据订单状态和订单类型控制按钮
      const array = []
      if (row.deliveryType === 2) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => getErrandFee(row),
          },
          {
            default: () => '跑腿询价',
          },
        ))
      }
      if (row.deliveryType === 21) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => openErandDetailsModel(row),
          },
          {
            default: () => '跑腿单',
          },
        ))
      }
      if (row.hasPrint === 0) {
        array.push(h(
          NPopconfirm,
          {
            onPositiveClick: async () => {
              printDrawerModelFunction(row)
              // printOrder.value = row
              // printShow.value = true
              // nextTick(() => {
              //   const vpn = new VuePrintNext({
              //     el: '#printMe',
              //     async closeCallback() { // 打印窗口的确认和取消按钮是由浏览器提供的，无法直接在 VuePrintNext 类中监听
              //       printShow.value = false
              //       // 默认选择了打印
              //       console.log('打印窗口已经关闭')
              //       await api.printOrder({ id: row.id })
              //       await refreshDate()
              //     },
              //   })
              //   console.log(vpn.$attrs)
              // })
              // refreshDate()
            },
            onNegativeClick: () => {
            },
          },
          {
            trigger: () => h(NButton, { 'size': 'small', 'v-print': 'print', 'type': 'primary', 'secondary': true }, { default: () => '打印' }),
            default: () => '一切都将一去杳然，任何人都无法将其捕获。',
          },
        ))
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => printDrawerModelFunction(row),
          },
          {
            default: () => '打印',
          },
        ))
      }
      // 待接单
      if (row.orderStatus === 0) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => confirmOrderFunction(row),
          },
          {
            default: () => '接单',
          },
        ))
      }
      // 待堂食取货
      if (row.orderStatus === 1) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => makingCompletedFunction(row),
          },
          {
            default: () => '制作完成',
          },
        ))
      }
      // 堂食取单
      if (row.deliveryStatus === 22) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => startDeliverFunction(row),
          },
          {
            default: () => '堂食取单',
          },
        ))
      }
      // 外卖取单
      if (row.deliveryType === 21) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => startDeliverFunction(row),
          },
          {
            default: () => '骑手取单',
          },
        ))
      }
      // 外卖取单
      if (row.deliveryStatus === 22) {
        array.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => startDeliverFunction(row),
          },
          {
            default: () => '自配发货',
          },
        ))
      }
      return array
    },
  },
]
const pagination11 = ref({
  page: 2,
  showSizePicker: true,
  sizes: [10, 15],
  onChange: (page) => {
    pagination11.value.page = page
  },
  onUpdatePageSize: (size) => {
    pagination11.value.size = size
    pagination11.value.page = 1
  },
})
const pagination12 = ref({
  page: 1,
  showSizePicker: true,
  sizes: [10, 15],
  onChange: (page) => {
    pagination12.value.page = page
  },
  onUpdatePageSize: (size) => {
    pagination12.value.size = size
    pagination12.value.page = 1
  },
})
const pagination21 = ref({
  page: 1,
  showSizePicker: true,
  sizes: [10, 15],
  onChange: (page) => {
    pagination21.value.page = page
  },
  onUpdatePageSize: (size) => {
    pagination21.value.size = size
    pagination21.value.page = 1
  },
})
const pagination22 = ref({
  page: 1,
  showSizePicker: true,
  sizes: [10, 15],
  onChange: (page) => {
    pagination22.value.page = page
  },
  onUpdatePageSize: (size) => {
    pagination22.value.size = size
    pagination22.value.page = 1
  },
})
// 生命周期
onMounted(async () => {
  refreshDate()
})
const globalTask = useGlobalTask()
onUnmounted(async () => {
  // 开启定时刷新任务
  globalTask.clearAllTimed()
})
async function refreshDate() {
  // 销售订单
  const todoParam = {
    orderStatusList: [0, 1, 2, 3],
  }
  const res = await api.getTodoSaleOrder2(todoParam)
  waitOrderData.value = res.waitConfirm
  makingOrderData.value = res.making
  inStoreOrder.value = res.inStoreOrder
  outStoreOrder.value = res.outStoreOrder
}
/**
 * d打印预览
 */

const printDrawerModel = ref(false)
const printOrder = ref({})
async function printDrawerModelFunction(delivetyOrderPO) {
  printDrawerModel.value = true // 打开抽取预览
  printOrder.value = await api.getOrderPO(delivetyOrderPO.orderPO.id)
}
async function printOrderFunction(_params) {
  // const vpn = new VuePrintNext({
  //   el: '#printMe',
  //   async closeCallback() { // 打印窗口的确认和取消按钮是由浏览器提供的，无法直接在 VuePrintNext 类中监听
  //     printShow.value = false
  //     // 默认选择了打印
  //     console.log('打印窗口已经关闭')
  //     // await api.printOrder({ id: row.id })
  //     // await refreshDate()
  //   },
  // })
}
// function timedTasksFunction() {
//   if (globalTask.timedSwitch) {
//     globalTask.clearAllTimed()
//   }
//   else {
//     const timedId = setInterval(() => {
//       refreshDate()
//     }, 3000)
//     globalTask.pushTimed(timedId)
//   }
// }

/**
 * 销售订单详情
 * @param row 销售数据
 */
function openOrderDetailsModel(row) {
  router.push({ path: `/order/sale-order-details/${row.id}`, query: { orderNum: row.orderPO.orderNum, orderId: row.orderPO.id } })
}
/**
 * 跑腿订单详情
 * @param row 销售数据
 */
function openErandDetailsModel(row) {
  router.push({ path: `/order/errand-order/${row.id}`, query: { errandId: row.errandOrder.id } })
}
// 接单接口
async function confirmOrderFunction(row) {
  try {
    card1Load.value = true
    await api.confirmOrder(row.id)
    await refreshDate()
  }
  finally {
    card1Load.value = false
  }
}
// 制作完成
async function makingCompletedFunction(row) {
  try {
    card1Load.value = true
    await api.makingCompleted(row.id)
    await refreshDate()
  }
  finally {
    card1Load.value = false
  }
}
// 取餐
async function startDeliverFunction(row) {
  try {
    card2Load.value = true
    await api.startDeliver({ id: row.id })
    await refreshDate()
  }
  finally {
    card2Load.value = false
  }
}

async function getErrandFee(row) {
  let dadaQueryFee = {}
  const m = $dialog.info({
    content: '你确定？',
    positiveText: '确定',
    negativeText: '自配',
    title: row.orderNum,
    onPositiveClick: async () => {
      try {
        card1Load.value = true
        await api.getDadaQueryFeeThen(dadaQueryFee)
        await refreshDate()
      }
      finally {
        card1Load.value = false
      }
    },
    onNegativeClick: async () => {
      try {
        card1Load.value = true
        await api.selfDeliver(row) // 自配
        await refreshDate()
      }
      finally {
        card1Load.value = false
      }
    },
  })
  m.content = '正在询价请稍后!!!'
  dadaQueryFee = await api.getDadaQueryFee(row.id)
  m.content = `配送距离 = ${dadaQueryFee.errandDistance}米，` + `跑腿费用 = ${dadaQueryFee.deliveryFee}元。`
}
function handleBeforeLeave(tabName) {
  card1Load.value = true
  card2Load.value = true
  switch (tabName) {
    case 'not-allowed':
      return false
    case 'wait':
    default:
      return true
  }
}
function handleUpdateValue() {
  card1Load.value = false
  card2Load.value = false
}
</script>

<style scoped>
/** */
:deep(.n-form-item-blank) {
  justify-content: flex-end;
}
:deep(.n-form-item-feedback-wrapper) {
  min-height: 0;
}
</style>
